<template>
  <div>
    <el-card shadow="hover">
      <CategorySelector @isDisablad="isDisablad" :prop="selectDisabled" />
    </el-card>
    <el-card shadow="hover" style="margin-top: 20px;" v-show="cardShow === 1">
      <el-button type="primary" size="small" @click="reviseSPU()" :disabled="disabledAdd">添加SPU</el-button>
      <el-table :data="spuList.records" border style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="spuName" label="SPU名称" width="180">
        </el-table-column>
        <el-table-column prop="description" label="SPU描述">
        </el-table-column>
        <el-table-column prop="address" label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-plus" size="mini" title="添加SKU"></el-button>
            <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="reviseSPU(scope.row)"
              title="修改SPU"></el-button>
            <el-button type="info" icon="el-icon-info" size="mini" title="查看SKU列表"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" title="删除SPU"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 20px; text-align: center;" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[2, 5, 10]" :page-size="100"
        layout="prev, pager, next, jumper, ->, sizes, total" :total="spuList.total || 0">
      </el-pagination>
    </el-card>
    <el-card style="margin-top: 20px;" v-show="cardShow === 2">
      <el-form :model="listForm" label-width="80px" :rules="rules">
        <el-form-item label="SPU名称" prop="spuName">
          <el-input v-model="listForm.spuName" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="trademarkId">
          <el-select v-model="listForm.trademarkId" placeholder="请选择">
            <el-option v-for="item in trademarkList" :key="item.id" :label="item.tmName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" prop="description">
          <el-input type="textarea" v-model="listForm.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片" prop="imgList">
          <el-upload :action="`${BASE_URL}/admin/product/fileUpload`" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="imgList" :on-success="uploadOk">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img w-full width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-select v-model="baseSaleAttrId" :placeholder="`还有${baseSaleAttrList.length}个未选择`" class="xxsx">
            <el-option v-for="item in baseSaleAttrList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button type="primary" size="small" @click="addSalesAttributes">添加销售属性</el-button>
        </el-form-item>
        <el-form-item>
          <el-table :data="trademarkData">
            <el-table-column type="index" label="序号" width="80" align="center">
            </el-table-column>
            <el-table-column prop="saleAttrName" label="属性名">
            </el-table-column>
            <el-table-column label="属性名称列表" width="180">
              <template slot-scope="scope">
                <el-button icon="el-icon-plus" size="mini" @click="checkInput(scope.$index)"
                  v-show="currentIndex !== scope.$index"></el-button>
                <el-input v-model="inputValue" size="mini" v-if="currentIndex === scope.$index" @blur="tagBlur(scope.row)"
                  ref="inp" style="width: 120px;"></el-input>
                <el-tag v-for="tag, index in scope.row.spuSaleAttrValueList" :key="tag.id" closable
                  @close="closeTag(scope.row.spuSaleAttrValueList, index)">
                  {{ tag.saleAttrValueName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="save">保存</el-button>
          <el-button size="small" @click="cancelSpuOperate">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Spu',
  data() {
    return {
      listForm: {    //表单数据
        spuName: '',   //spu名称
        trademarkId: '',
        description: '',  //spu描述
        imgList:''
      },
      currentPage: 1, //分页器
      pageSize: 2,   //分页器
      total: 0,    //分页器


      cardShow: 1,

      baseSaleAttrId: '',
      BASE_URL: process.env.VUE_APP_BASE_API, //环境变量
      dialogImageUrl: '',    //上传图片
      dialogVisible: false,  //上传图片
      currentIndex: -1,     //表格spu属性值输入框和按钮切换
      inputValue: '',         //spu输入框输入的属性值
      disabledAdd: true,    //控制按钮禁用
      selectDisabled: false,  //控制3级分类选项是否禁用 
      rules: {      //表单验证
        spuName: [
          { required: true, message: '请输入SPU名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        trademarkId: [
          { required: true, message: '请选择品牌', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入SPU描述', trigger: 'blur' },
          { min: 3, max: 25, message: '长度在 3 到 25 个字符', trigger: 'blur' }
        ],
        imgList:[]
      }
    }
  },
  methods: {
    handleSizeChange(val) {   //分页器
      this.pageSize = val
      this.currentPage = 1
      this.$store.dispatch('spu/getSpuList', { id3: this.id3, page: this.currentPage, size: val })
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {   //分页器
      this.currentPage = val
      this.$store.dispatch('spu/getSpuList', { id3: this.id3, page: val, size: this.pageSize })
      console.log(`当前页: ${val}`);
    },
    cancelSpuOperate() {  //取消spu修改和添加
      this.cardShow = 1
      this.$store.commit('spu/RESET_SPULIST')   //清空存在vuex中的列表数据
      this.listForm.spuName = ''        //清空SPU名称
      this.listForm.description = ''    //清空SPU描述
      this.selectDisabled = false
      //重新获取spuList数据
      this.currentPage = 1     //有问题，可以保存当前页面，但是页码会回到1,所以干脆统一回第一页
      this.$store.dispatch('spu/getSpuList', { id3: this.id3, page: this.currentPage, size: this.pageSize })
    },
    reviseSPU(row) {    //添加或者修改spu
      this.selectDisabled = true
      this.cardShow = 2  //切换显示
      this.$store.dispatch('spu/getBaseSaleAttrList')  //1请求
      this.$store.dispatch('spu/getTrademarkList')     //2请求
      if (row) {  //修改额外获取2个
        this.$store.dispatch('spu/getSpuImageList', row.id)   //3请求
        this.$store.dispatch('spu/getSpuSaleAttrList', row.id)  //4请求
        this.listForm.spuName = row.spuName
        this.listForm.description = row.description
      }
      // this.$store.commit('SPU_LIST_ONE',{spuName:row.spuName,description:row.description})
    },
    addSalesAttributes() {    //添加销售属性
      //先通过id找到选中的属性值
      const saleAttrName = this.baseSaleAttrList.filter((item) => {
        return item.id === this.baseSaleAttrId
      })
      const data = {
        saleAttrName: saleAttrName[0].name,
        spuSaleAttrValueList: []
      }
      this.$store.commit('spu/ADD_SPUSALEATTRLIST', data)  //添加销售属性
      this.$store.commit('spu/SIFT_BASESALEATTRLIST')   //过滤销售属性
      this.baseSaleAttrId = ''
    },
    handleRemove(file, fileList) {    //上传图片的删除图片的回调
      console.log(file, fileList, '-------');
    },
    handlePictureCardPreview(file) {   //查看图片的回调
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadOk(response, file, fileList) {   //图片上传成功的回调
      console.log(response, file, fileList)
    },
    checkInput(index) {       //销售属性按钮和input框切换
      this.currentIndex = index
      this.$nextTick(() => {    //页面更新以后才能拿到ref，input的显示要用v-if，不然出来的多个ref对象带同一个标识，获取焦点只会生效最后一个
        this.$refs.inp.focus()
      })
    },
    tagBlur(row) {          //销售属性按钮和input框切换
      this.currentIndex = -1
      console.log(this.inputValue)
      console.log(row)
      if (this.inputValue) {   //输入不为空才会添加
        row.spuSaleAttrValueList.push({ id: Date.now(), saleAttrValueName: this.inputValue })
        this.inputValue = ''  //清空输入内容
      }
    },
    closeTag(spuSaleAttrValueList, index) {              //删除销售属性值tag时的回调
      spuSaleAttrValueList.splice(index, 1)          //因为是响应式数据中的属性，也是响应式的
    },
    isDisablad(val) {    //如果3级id存在添加按钮就显示
      if (val) {
        this.disabledAdd = false
      } else {            //不存在就禁用
        this.disabledAdd = true
      }
    },
    save() {     //点击保存
      console.log(this.ruleForm.spuName)
    }
  },
  computed: {
    ...mapState({
      spuList: state => state.spu.spuList,
      id3: state => state.spu.id3,
      baseSaleAttrList: state => state.spu.BaseSaleAttrList,
      trademarkList: state => state.spu.TrademarkList,
      spuImageList: state => state.spu.spuImageList,
      trademarkData: state => state.spu.trademarkData
    }),
    imgList() {
      return this.spuImageList.map(item => {
        return {
          name: item.imgName,
          url: item.imgUrl
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
